package com.lhd.qd.module.system.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lhd.qd.common.annotation.OperateLog;
import com.lhd.qd.common.annotation.Permission;
import com.lhd.qd.common.base.ApiResult;
import com.lhd.qd.common.base.BaseController;
import com.lhd.qd.common.exception.BusinessException;
import com.lhd.qd.module.system.user.model.dto.UserPageQuery;
import com.lhd.qd.module.system.user.model.dto.UserSaveDTO;
import com.lhd.qd.module.system.user.model.vo.UserDetailVO;
import com.lhd.qd.module.system.user.model.vo.UserListVO;
import com.lhd.qd.module.system.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户")
@RequestMapping("user")
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "分页列表", response = UserListVO.class)
    @GetMapping
    public ResponseEntity<ApiResult<IPage<UserListVO>>> pageUser(UserPageQuery query) {

        return success(userService.pageUser(query));
    }

    @ApiOperation(value = "详情", response = UserDetailVO.class)
    @GetMapping("{id}")
    public ResponseEntity<ApiResult<UserDetailVO>> getUserById(@PathVariable("id") Long id) {

        return success(userService.getUserById(id));
    }

    @OperateLog
    @Permission
    @ApiOperation(value = "新增")
    @PostMapping
    public ResponseEntity<ApiResult> saveUser(@Validated @RequestBody UserSaveDTO saveDTO) {

        return successOrFail(userService.saveUser(saveDTO));
    }

    @OperateLog
    @Permission
    @ApiOperation(value = "修改")
    @PutMapping("{id}")
    public ResponseEntity<ApiResult> updateUserById(@PathVariable("id") Long id, @Validated @RequestBody UserSaveDTO saveDTO) {

        return successOrFail(userService.updateUserById(id, saveDTO));
    }

    @OperateLog
    @Permission
    @ApiOperation(value = "删除")
    @DeleteMapping("{id}")
    public ResponseEntity<ApiResult> removeUserById(@PathVariable("id") Long id) {

        if (id == 1) {
            throw new BusinessException("超级管理员不允许被删除");
        }

        return successOrFail(userService.removeUserById(id));
    }
}
